.PHONY: all clean
MKDIR = mkdir
RM = rm
RMFLAGS = -fr
CC = gcc
DIR_OBJS = objs
DIR_EXES = exes
DIR_DEPS = objs
DIRS = $(DIR_OBJS) $(DIR_EXES) 
EXE = complicated
EXE := $(addprefix $(DIR_EXES)/, $(EXE))
SRCS = $(wildcard *.c)
OBJS = $(SRCS:.c=.o)
OBJS := $(addprefix $(DIR_OBJS)/, $(OBJS))
DEPS = $(SRCS:.c=.dep)
DEPS := $(addprefix $(DIR_DEPS)/, $(DEPS))
CFLAGS+=-Iinclude

all: $(EXE)

ifeq ("$(wildcard $(DIR_DEPS))", "")
DEPS_DIR_DEPS := $(DIR_DEPS)
endif

ifneq ($(MAKECMDGOALS), clean)
-include $(DEPS)
endif

$(DIRS):
	$(MKDIR) $@

$(EXE): $(DIR_EXES) $(OBJS) $(DEPS)
	$(CC) -o $@ $(filter %.o, $^)

$(DIR_OBJS)/%.o: $(DIR_OBJS) %.c
	$(CC) $(CFLAGS) -o $@ -c $(filter %.c, $^)

$(DIR_DEPS)/%.dep: $(DEPS_DIR_DEPS) %.c
	@echo "Making $@ ..."
	@set -e; \
    	$(RM) $(RMFLAGS) $@.tmp; \
        $(CC) $(CFLAGS) -E -MM $(filter %.c, $^) > $@.tmp; \
		sed 's,\(.*\)\.o[ :]*,objs/\1.o $@: ,g' < $@.tmp >$@; \
		$(RM) $(RMFLAGS) $@.tmp

clean:
	$(RM) $(RMFLAGS) $(DIRS)



